<template>
  <div class="container_box">
    <div class="head_box">
      <!-- 首页导航栏 -->
      <el-menu mode="horizontal" router :default-active="activeIndex">
        <el-menu-item v-for="(item, index) in menu" :index="item.id" :key="index">{{ item.Name }}</el-menu-item>
        <!-- 登录按钮 -->
        <div style="text-align: right; display: flex; margin-left: 89%;">
          <div style="margin-top: 15px;">
            <el-button v-if="logining == true" type="success" size="small" @click="clockVisible = true"
              style="margin-right: 20px; margin-top: -100px;">每日打卡</el-button>
          </div>
          <div style="margin-top: 15px;">
            <el-button type="primary" size="small" @click="helperVisible = true"
              style="margin-right: 20px; margin-top: -100px;">在线客服</el-button>
          </div>
          <span v-if="logining == false" slot="reference"
            style="height: 40px; width: 40px; text-align: center; line-height: 40px; border-radius: 25px; 
                                  background: skyblue; color: white; display: inline-block; font-size: 10px; margin-right: 30px; margin-top: 6px;"
            @click="selectLogin">登录</span>
          <el-dropdown>
            <img v-if="logining" class="user-images"
              src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" alt="" style="width: 40px;
                                        height: 40px;
                                        border-radius: 50%;
                                        margin-right: 30px; 
                                        margin-top: 6px;">
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native.prevent="updatePassword">修改密码</el-dropdown-item>
              <el-dropdown-item @click.native.prevent="outLogin">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-menu>
    </div>

    <div class="login_box">
      <!--登录弹框-->
      <el-dialog style="text-align: center;" title="用户登录" :visible.sync="loginDialogVisible" width="30%"
        @close="dialogClosed">
        <!--文字链接切换登录-->
        <el-link @click="loginByAccount" style="margin-bottom: 30px; border-left: 10px;">账号密码</el-link>
        <el-link @click="loginByPhone" style="margin-bottom: 30px;margin-left: 30px;">手机验证</el-link>
        <!--账号登录表单-->
        <el-form key="account" v-if="showAccount" :model="loginForm_account" :rules="loginAccount_rules" ref="loginRef"
          label-width="70px">
          <el-form-item label="账户" prop="username">
            <el-input v-model="loginForm_account.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm_account.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="图片" style="text-align: left">
            <img width="200px" style="margin-left: 10px;" :src="url" @click="getNewPicture">
          </el-form-item>
          <el-form-item label="验证码" prop="verifyCode">
            <el-input v-model="loginForm_account.verifyCode"></el-input>
          </el-form-item>
        </el-form>

        <!--手机登录表单-->
        <el-form key="phone" v-if="showPhone" :model="loginForm_phone" :rules="loginPhone_rules" ref="loginRef"
          label-width="70px">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="loginForm_phone.phone"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="msgCode" style="text-align: left;">
            <el-input v-model="loginForm_phone.msgCode" style="width:150px;"></el-input>
            <el-button v-if="getCode == false" :disabled="disabled" style="margin-left: 30px;" type="primary"
              @click="getPhoneCode">
              获取验证码
            </el-button>
            <el-button v-if="getCode" :disabled="disabled" style="margin-left: 30px;" type="primary"
              @click="getPhoneCode">
              {{ countDown }}秒后重新发送
            </el-button>
          </el-form-item>
        </el-form>
        <el-button type="success" @click="login">登录</el-button>
      </el-dialog>
    </div>

    <el-dialog style="text-align: center;" title="在线客服" :visible.sync="helperVisible" width="20%">
      <template>
        <div>
          <iframe style="height: 50vh; width: 100%; "
            src="https://chatbot.aliyuncs.com/intl/index.htm?from=khLIrbWtWd&locale=zh-CN" scrolling="no"
            frameborder="0"></iframe>
        </div>
      </template>
    </el-dialog>
    <!--打卡表单-->
    <el-dialog style="text-align: center;" title="健康打卡" :visible.sync="clockVisible" width="30%"
      @close="clockDialogClosed">
      <el-form ref="clock_ref" :model="clock_form" :rules="clock_rules">
        <el-form-item label="当前体温" style="text-align: left" prop="clockContent">
          <el-input v-model="clock_form.clockContent" style="width: 100px"
            oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="所在地点" style="text-align: left; display: flex">
          <span>{{ address }}</span>
          <el-button @click="getLocation" style="margin-left: 10px">获取当前位置</el-button>
        </el-form-item>
        <el-form-item label="文件上传" style="text-align: left; display: flex">
          <el-button size="small" type="primary" @click="fileVisible = true">点击上传</el-button>
        </el-form-item>
        <el-dialog style="text-align: center;" title="文件上传" :visible.sync="fileVisible" width="37%"
          @close="fileDialogClosed" append-to-body>
          <el-form ref="file_ref">
            <el-upload class="upload-demo" drag action="action" multiple :before-upload="beforeUpload"
              :show-file-list="true" :auto-upload="false" :http-request="upload" ref="uploadBox">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip" style="text-align: center;">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitFile">上传文件</el-button>
        </el-dialog>
      </el-form>
      <el-button type="success" @click="clockSubmit">打卡</el-button>
    </el-dialog>
    <!--修改密码表单-->
    <el-dialog style="text-align: left;" title="修改密码" :visible.sync="pwdVisible" width="30%"
      @close="passwordDialogClosed">
      <el-form ref="pwd_Ref" :model="pwd_form" :rules="pwd_rules" label-position="right" label-width="80px">
        <el-form-item label="当前密码">
          <el-input v-model="pwd_form.oldPassword" style="width: 50%"></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="pwd_form.newPassword" style="width: 50%"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        <el-button type="success" @click="passwordSubmit">修改</el-button>
      </div>

    </el-dialog>

    <div class="main">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
const formData = new FormData()
import {
  GetLoginPictureAPI,
  PostLoginPictureAPI,
  PostLoginByAccountAPI,
  GetLoginCodeAPI,
  PostLoginByPhoneAPI,
} from '@/components/utils/api/login_api.js'


import { getCurrentInstance } from 'vue';

// 打卡接口
import { ClockAPI } from '@/components/utils/api/clock_api.js'
// 获取图片文件返回绑定信息
import { postImage } from '@/components/utils/api/sysfile_api.js'

import { GetUserBaseInformationAPI, getHeadImgAPI, UpdatePasswordAPI, GetRoleAPI } from '@/components/utils/api/user_api.js'

import { router } from '@/router/index.js'

export default {
  data() {
    const valiNumberPass1 = (rule, value, callback) => {//包含小数的数字
      let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
      if (value === '') {
        callback(new Error('请输入内容'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字'));
      } else {
        callback();
      }
    };
    return {
      haveClick: false,// 判断是否点击文件上传
      pwdVisible: false, // 密码弹窗显示
      pwd_form: {},// 密码form
      address: '',// 地址拼接
      pwd_rules: {},// 密码规则
      location: [],
      clock_form: {},
      afiles: [],
      fileList: [],
      clockVisible: false,
      fileVisible: false,
      menu: [
        {
          "id": "/epidemicConsultation",
          "Name": "疫情资讯"
        },
        {
          "id": "/epidemicKnowledge",
          "Name": "疫情知识"
        },
        {
          "id": "/epidemicNotification",
          "Name": "疫情通知"
        },
        {
          "id": "/epidemicData",
          "Name": "疫情数据"
        }
      ],
      url: '',
      logining: false,
      loginDialogVisible: false,
      loginForm_account: { username: '20191001', password: '123', verifyCode: '' },
      loginForm_phone: { phone: '13049049925', code: '' },
      clock_rules: {
        clockContent: [{
          required: true, validator: this.valiNumberPass1, message: '请输入体温', trigger: "blur"
        }],
      },
      loginAccount_rules: {
        username: [{
          required: true, message: '请输入账号'
        }],
        password: [{
          required: true, message: '请输入密码'
        }],
        verifyCode: [{
          required: true, message: '请输入验证码'
        }],
      },
      loginPhone_rules: {
        phone: [{
          required: true, message: '请输入手机号'
        }],
        msgCode: [{
          required: true, message: '请输入验证码'
        }],
      },
      annexId: '',
      activeIndex: '',
      showAccount: true,
      showPhone: false,
      params: {},
      url: '',
      getCode: false,
      disabled: false, // 按钮是否可用
      countDown: 60,// 倒计时时间（单位：秒）
      helperVisible: false
    }
  },
  created() {
    this.getPicture()
    this.getLogin()
    const { proxy } = getCurrentInstance();
    this.url = proxy.$router.currentRoute.fullPath
  },
  methods: {
    //上传文件前
    beforeUpload(file) {
      if (file) {
        formData.append('afiles', file)
        console.log("🚀 ~ file: Home.vue:251 ~ beforeUpload ~ formData:", formData)
      }
      else {
        this.$message.error("上传文件时出错")
      }
    },

    submitFile() {
      this.$refs.uploadBox.submit()
      this.fileVisible = false
    },

    //上传
    upload() {
      postImage(formData).then(res => {
        if (res.data.code == 200) {
          res.data.data.forEach(element => {
            this.annexId = element.id
          });
          this.$message.success("上传文件成功")
        } else {
          this.$message.error("上传文件失败")
        }
      })
    },
    // 修改密码
    updatePassword() {
      this.pwdVisible = true
    },

    //打卡提交
    clockSubmit() {
      if (formData == null) {
        ClockAPI(params).then(res => {
          if (res.data.code == 200) {
            this.clockVisible = false,
              this.$message.success(res.data.message)
            window.location.reload()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
      else if (formData != null) {
        //  this.$refs.uploadBox.submit()
        var params = {
          clockStatus: 0,
          annexId: this.annexId,
          clockLocation: this.address,
          clockContent: this.clock_form.clockContent
        }
        ClockAPI(params).then(res => {
          if (res.data.code == 200) {
            this.clockVisible = false,
              this.$message.success(res.data.message)
            window.location.reload()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }

    },

    //登出操作
    outLogin() {
      this.$message.success('登出成功')
      // this.menu.remove
      sessionStorage.clear()
      if (this.url != "/epidemicConsultation") {
        this.$router.push('/epidemicConsultation')
        window.location.reload()
      }
      else if (this.url == "/epidemicConsultation") {
        window.location.reload()
      }
    },

    // 修改密码
    passwordSubmit() {
      UpdatePasswordAPI({
        id: sessionStorage.getItem('userId'),
        newPassword: this.pwd_form.newPassword,
        oldPassword: this.pwd_form.oldPassword
      }).then(res => {
      })
    },
    //登录按钮操作
    selectLogin() {
      this.loginDialogVisible = true
      this.getNewPicture()
    },

    //获取手机验证码
    getPhoneCode() {
      this.getCode = true
      this.disabled = true; // 禁用按钮
      let timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--;
        } else {
          clearInterval(timer);
          this.disabled = false; // 启用按钮
          this.countDown = 60; // 重置倒计时时间
          this.getCode = false
        }
      }, 1000);
      var params = {
        "phone": this.loginForm_phone.phone
      }
      GetLoginCodeAPI(params).then(res => {
        if (res.data.message == "一分钟内不允许重复发送") {
          this.$message.erorr(res.data.message)
        }
        else {
          this.$message.success(res.data.message)

        }
      })
    },

    // 判断是否登录
    getLogin() {
      if (sessionStorage.getItem('token')) {
        this.menu.push({
          "id": "/personalcenter",
          "Name": "个人中心"
        })
        this.logining = true
      }
    },

    //登录
    async login() {
      if (this.showAccount == true) {
        PostLoginPictureAPI(this.loginForm_account.verifyCode).then(res => {
          if (res.data === true) {
            PostLoginByAccountAPI(this.loginForm_account).then(res => {
              if (res.data.data.token == "") {
                this.$message.error("请检查账号密码是否正确")
              }
              else {
                this.$message.success('登录成功')
                sessionStorage.setItem('token', res.data.data.token)
                var params = {
                  token: res.data.data.token.substring(9, sessionStorage.getItem('token').length),
                  systemModelCode: "-1"
                }
                GetUserBaseInformationAPI(params).then(res1 => {
                  sessionStorage.setItem('userId', res1.data.userId)
                  sessionStorage.setItem('role', res1.data.roleName)
                  window.location.reload()
                })
                this.loginDialogVisible = false
              }
            })
          }
          else {
            this.$message.error("请输入正确的验证码")
            this.getNewPicture()
          }
        })
      }
      if (this.showPhone == true) {
        await PostLoginByPhoneAPI(this.loginForm_phone).then(res => {
          if (res.data.code == 200) {
            this.$message.success('登录成功')
            sessionStorage.setItem('token', res.data.data.token)
            var params = {
              token: res.data.data.token.substring(9, sessionStorage.getItem('token').length),
              systemModelCode: "-1"
            }
            GetUserBaseInformationAPI(params).then(res1 => {
              console.log("file: Home.vue:397  res1", res1)
              sessionStorage.setItem('userId', res1.data.userId)
              sessionStorage.setItem('role', res1.data.roleName)
              window.location.reload()
            })
            this.loginDialogVisible = false
          }
          else {
            this.$message.error(res.data.message)
          }
        })
      }
    }
    ,

    //点击刷新验证码图片
    getNewPicture() {
      this.getPicture()
    },

    //获取验证码图片
    getPicture() {
      GetLoginPictureAPI().then(res => {
        let url = res.data.data.imageBase64
        this.url = 'data:image/png;base64,' + url;
      })
    },

    //对话框消失，表单重置
    dialogClosed() {
      this.$refs.loginRef.resetFields()
    },

    //切换登录状态
    loginByAccount() {
      this.showAccount = true,
        this.showPhone = false
    },

    //切换登录状态
    loginByPhone() {
      this.showAccount = false,
        this.showPhone = true
    },

    //打卡弹窗关闭重置
    clockDialogClosed() {
      this.$refs.clock_ref.resetFields()
      this.address = ""
    },

    // 密码修改弹窗关闭重置
    passwordDialogClosed() {
      this.$refs.pwd_Ref.resetFields()
    },

    //打卡弹窗关闭重置
    fileDialogClosed() {
      this.afiles = ""
    },

    //获取用户位置信息
    getLocation() {
      this.$jsonp(
        'https://apis.map.qq.com/ws/location/v1/ip?',
        {
          key: 'XXUBZ-7ZHL4-Q3BU6-X63FP-DWA36-DHBQ5',
          output: 'jsonp'
        }
      ).then(res => {
        this.location = res.result.ad_info
        this.address = this.location.province + this.location.city + this.location.district
      })
    }
  },

  // watch: {
  //   $router: {
  //     handler: function(router) {
  //     },
  //     immediate: true
  //   }
  // },

}
</script>
<style lang="less" scoped>
.main {
  height: 100%;
}

.zzzz {
  position: fixed;
  width: 50%;
  height: 50%;
  top: 0;
  left: 0;
}
</style>